import mConfig from '@/config/base.js'
import md5Libs from "@/common/md5.js"
import $store from '../store'

class comm{
	
//========【用户操作】=================================================
		
	//获取用户缓存信息
	getUser($refresh=false){
		if($refresh){
			return new Promise((resolve, reject) => {	
				uni.$u.api.userInfo().then(res=>{
					$store.commit('login',res.data)
					resolve(res.data.memeber)
				})
			})
		}else{
			return $store.state.$userInfo||''
		}
	}

//========【常用操作】=================================================
	
	//判断是否成功获取信息
	isok(res,tips=false){
		if(res.errno == 0 && res.message == 'ok'){
			return res;
		}else{
			if(tips) this.error(res.message);
			return false;
		}
	}
	
	// 跳转页面
	a(path,data = '',type = 1){
		if(path==''){
			return;
		}else if(path==0){
			this.toBack(1,true);	//后退强制刷新
		}else if(path==-1){
			uni.navigateBack();		//后退不刷新
		}else{
			var p = path.indexOf('pages/');
			if(p == -1){
				var x = path.indexOf('/');
				if(x>-1){
					path='pages/'+path;
				}else{
					path='pages/index/'+path;
				}
			}
			
			if(data === '') data={};
			switch(type){
				case 1:
					type='navigateTo';
					break;
				case 2:
					type='reLaunch';
					break;
				case 3:
					type='switchTab';
					break;
				case 4:
					type='redirectTo';
					break;
			}

			uni.$u.route({
				url: path,
				type : type,
				params: data,
			});	
		}
		return;
	}
	
	// 缓存本地数据
	F(key,val = undefined,exp = 0){
		let nowtime = Math.floor(Date.parse(new Date()) / 1000);
		if(val == undefined){
			if(key == '' ){		//清除所有缓存
				uni.clearStorageSync();
			}else{					//读取缓存
				let cache = uni.getStorageSync(key+'_exp');
				let val = uni.getStorageSync(key);
				if(cache == '' || cache == undefined){		//没有缓存
					return val;
				}else{
					if(nowtime - cache >0){					//超时
						return '';
					}else{
						return val;
					}
				}
			}
		}else if(val == '' || val== null){		//删除缓存
			uni.removeStorageSync(key);
		}else{						//设置缓存
			if(exp >0 ){
				let time = nowtime + exp * 60;
				uni.setStorageSync(key+'_exp',time);
			}
			uni.setStorageSync(key,val);
		}
	}
	
	// 获取系统配置数据
	async getConfig(){
		let data = this.F('config');
		if(data=='' || data == undefined){
			return await uni.$u.api.getConfig().then(res => {
				this.F('config',res.data,30);
				$store.commit('setConfig',res.data)
				return res.data;
			});
		}else{
			return await data;
		}
	}
	
	//对象格式化成JSON格式
	toJson(data){
		return JSON.parse(JSON.stringify(data));
	}
	
	toBack(delta = 1 , refresh = true){
		if(refresh == true){
			let page = getCurrentPages();   //跳转页面成功之后
			if (!page) return;

			page=page[page.length - 2];	//获取上一页的路径
			//#ifdef MP-WEIXIN
			// 如果扫码传参的Q值不为空，则进行encodeURIComponent转义，避免数据丢失
			if(page.options.q != undefined){
				page.options.q = encodeURIComponent(page.options.q);
			}
			let url=page.route
			let data=page.options ?? {}
			//#endif
			
			//#ifdef MP-ALIPAY
			let url=page.$page.fullPath
			let data=''
			//#endif
			
			this.a(url,data,2)
			
		}else{
			uni.navigateBack({
				delta:delta,
				success: function() {
				}
			});
		}
	}
	
	//HTML标签转义
	html_encode(str){ 
	   var s = ""; 
	   if (str.length == 0) return ""; 
	   s = str.replace(/&/g, "&amp;"); 
	   s = s.replace(/</g, "&lt;"); 
	   s = s.replace(/>/g, "&gt;"); 
	   s = s.replace(/ /g, "&nbsp;"); 
	   s = s.replace(/\'/g, "&#39;"); 
	   s = s.replace(/\"/g, "&quot;"); 
	     s = s.replace(/\n/g, "<br/>"); 
	   return s; 
	 } 
	 
	 html_decode(str){ 
	   var s = ""; 
	   if (str.length == 0) return ""; 
	   s = str.replace(/&amp;/g, "&"); 
	   s = s.replace(/&lt;/g, "<"); 
	   s = s.replace(/&gt;/g, ">"); 
	   s = s.replace(/&nbsp;/g, " "); 
	   s = s.replace(/&#39;/g, "\'"); 
	   s = s.replace(/&quot;/g, "\""); 
	   s = s.replace(/<br\/>/g, "\n"); 
	   return s; 
	 } 

//========【对象数组操作】=================================================

	//移除数组某个项
	remove(array,val){
		let index = array.indexOf(val);
		if (index > -1) {
			array.splice(index, 1);
		}
		return array;
	}
	
	// 返回数组的长度，如果是空数组，返回0
	arrayLength(data){
		if(data==null || data==undefined || data.length==0){
			return 0;
		}else{
			return data.length;
		}
	}

//========【提示操作】=================================================
	
	//操作成功提示
	success(title,path='',type=1,time=2000){
		uni.showToast({
			title: title,
			duration:time,
		});
		let than = this;
		if(path==-1) path=0;
		if(path!=''){
			setTimeout(function(){
				than.a(path,'',type);
			},time+200);
		}
	}
	
	//错误提示
	error(title,path='',type=1,time=2000){
		uni.showToast({
			title: title,
			icon:'none',
			duration:time,
		});
		let than = this;
		if(path!=''){
			setTimeout(function(){
				than.a(path,'',type);
			},time+300);
		}
	}
	
	//警告提示
	info(title,path='',type=1,time=2000){
		uni.showToast({
			title: title,
			icon:'none',
			duration:time,
		});
		let than = this;
		if(path!=''){
			setTimeout(function(){
				than.a(path,'',type);
			},time+300);
		}
	}
	
	//弹窗提示
	tips(content,title='温馨提示'){
		uni.showModal({title:title ,content: content,showCancel:false});
	}
	
	//输出调试结果
	p(data,name=''){
		if(name!='') console.log('***********【'+name+'】***********');
		console.log(JSON.stringify(data));
	}
	
	//页面提示框
	tbox(title,type="warning"){
		return {
			show:true,
			title:title,
			type:type,
		}
	}
	
	//广告跳转
	adJump(res,c={}){
		if(res.linktype == '0'){					//跳转内部网页
			this.a(res.linkurl);
		}else if(res.linktype == '1'){				//跳转外部小程序
			// #ifdef MP-WEIXIN || H5
				uni.navigateToMiniProgram({
					appId: res.miniappid,
					path: res.minipath,
					extraData: {},
					success(res) {}
				})
			// #endif
			// #ifdef MP-ALIPAY
				if(res.ali_appid==''){			//跳外部H5网页
					my.ap.openURL({
						url: res.ali_path,
						success: (res) => {},
						fail: (err) => {
							console.log(JSON.stringify(err));
						}
					});
				}else{
					uni.navigateToMiniProgram({
						appId: res.ali_appid,
						path: res.ali_path,
						envVersion:'release',	//支付宝小程序需要选择版本，'release'代表线上版本
						extraData: {},
						success(res) {}
					})					
				}
			// #endif			
		}else if(res.linktype == '2'){				//打电话
			uni.makePhoneCall({
				phoneNumber: res.mobile,
			});
		}else if(res.linktype == '3'){				//打开地图导航
			uni.openLocation({
				latitude: res.lat,
				longitude: res.lng,
				scale:18,
				name : res.mapname,
				address: res.mapaddress,
				success: function () {
					console.log('success');
				},
				fail(e) {
					console.log(e);
				}
			});
		}else if(res.linktype == '4'){
			this.F('web_url',res.linkurl);
			this.a('index/html');
		}else if(res.linktype == '5'){		//跳转微信客服
			//#ifdef H5
			window.location.href=c.common.service_url;
			//#endif
		}else if(res.linktype == '6'){		//跳转企业微信客服
			//#ifdef H5
			window.location.href=c.common.service_url;
			//#endif
			//#ifdef MP-WEIXIN
			wx.openCustomerServiceChat({
			  extInfo: {url: c.common.service_corp_url},
			  corpId: c.common.service_corpid,
			  success(res) {}
			})
			//#endif
		}
	}
	
	getDate(time = null, fmt = 'yyyy-mm-dd') {
		// 如果为null,则格式化当前时间
		var dateTime = Number(new Date());
		//if (time) dateTime=time;
		// 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
		if(time != null){
			dateTime = dateTime + time*86400*1000;
		}
		let date = new Date(dateTime);
		let ret;
		let opt = {
			"y+": date.getFullYear().toString(), // 年
			"m+": (date.getMonth() + 1).toString(), // 月
			"d+": date.getDate().toString(), // 日
			"h+": date.getHours().toString(), // 时
			"M+": date.getMinutes().toString(), // 分
			"s+": date.getSeconds().toString() // 秒
			// 有其他格式化字符需求可以继续添加，必须转化成字符串
		};
		for (let k in opt) {
			ret = new RegExp("(" + k + ")").exec(fmt);
			if (ret) {
				fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
			};
		};
		return fmt;
	}
	
	//获取分享信息
	getShare(type=1){
		// #ifdef MP-WEIXIN
			let client=1
		// #endif
		// #ifdef MP-ALIPAY
			let client=2
		// #endif
		
		let data={ 
			url:'pages/index/index',
			type:type,
			client:client
		}
		return new Promise((resolve, reject) => {
			uni.$u.api.share(data).then(res=>{
				//获取分享连接的情况下， 更新
				if(type === 1){
					$store.commit('setShare',res.data)
				}
				resolve(res.data)
			})
		})
	}
	
	// 获取scene的值
	getScene(option,key=''){
		let scene='';
		//#ifdef H5
		scene=option.scene;
		//#endif
		//#ifdef MP-WEIXIN || MP-ALIPAY
		if (option?.query?.scene) {
			// 新规则：直接通过 options.scene
			scene = decodeURIComponent(option.query.scene);
		} else if (option?.scene) { 
			// 旧规则：通过 options.query.scene
			scene = decodeURIComponent(option.scene);
		}else if(option.q != undefined){		//扫二维码打开
			scene=decodeURIComponent(option.q);
			// console.log(scene);
			if(key===''){				
				// 直接返回获取的q参数
			}else if(key=='URL'){					//提取URL和传参
				scene=this.urlGetToJson(scene,false);
			}else{
				scene=this.urlGetToJson(scene);
				if(key!='GET'){						//提取所有传参
					scene=scene[key]??'';
				}
			}
		}
		//#endif
		
		if(scene!=null && scene!=undefined && scene!=''){
			return scene
		}else{
			return '';
		} 
	}
	
	// 网址参数转化为json,get为true，只提取参数
	urlGetToJson(url,get=true){
		var params = {};
		var paramStr = url.split('?')[1]; // 获取URL中的参数部分

		if (paramStr){
			var paramArr = paramStr.split('&'); // 将参数字符串分割为键值对数组
			for (var i = 0; i < paramArr.length; i++) {
				var param = paramArr[i].split('='); // 将键值对字符串分割为键和值
				var paramName = decodeURIComponent(param[0]); // 对键进行解码
				var paramValue = decodeURIComponent(param[1]); // 对值进行解码
				params[paramName] = paramValue; // 将键值对添加到params对象中
			}
		}
		
		if(get){			//只提取参数
			return params;
		}else{				//提取网址和参数			
			let pathUrl = url.split('?')[0];
			return {path:pathUrl,get:params};
		}
		
	}
	
	//跳转到登录页面
	toLogin(){
		//#ifdef MP-WEIXIN || MP-ALIPAY
		let url='/pages/user/login/index';
		//#endif
		//#ifdef H5
		let url='/pages/user/h5_login';
		//#endif
		this.a(url);
	}
	
	// 获取定位参数
	uniGetLoaction(options = {}){
		// 默认使用全局的配置
		const useFuzzy = options.useFuzzy !== undefined ? options.useFuzzy : mConfig.useFuzzy;
		const { success, fail } = options;
		
		// 根据 useFuzzy 选择定位方法
		const locationMethod = useFuzzy ? uni.getFuzzyLocation : uni.getLocation;

		locationMethod({
			type: 'gcj02',
			success: (res) => {
				if (typeof success === 'function') {
					success(res);
				}
			},
			fail: (error) => {
				if (typeof fail === 'function') {
					fail(error);
				}
			}
		});
	}

}
export default new comm();